#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <pthread.h>

const int threadnum = 5;

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void* WaitRun(void* args) {
    std::string name = static_cast<const char*>(args);
    // 使用条件变量，使得线程按照顺序打印
    while (true) {
        pthread_mutex_lock(&gmutex);
        pthread_cond_wait(&gcond, &gmutex);
        std::cout << "I am a thread, name: " << name << std::endl;
        usleep(10000);
        // pthread_cond_signal(&gcond);
        pthread_mutex_unlock(&gmutex);
    }
    return nullptr;
}

int main() {
    std::vector<pthread_t> threads;
    for (int i = 1; i <= threadnum; i++) {
        std::string* name = new std::string;
        *name += "thread-" + std::to_string(i);
        pthread_t tid;
        pthread_create(&tid, nullptr, WaitRun, (void*)name->c_str());
        threads.push_back(tid);
    }

    while (true) {
        // 在主线程中不断的唤醒其他线程
        pthread_cond_signal(&gcond);
        sleep(1);
    }

    for (auto& t : threads)
        pthread_join(t, nullptr);

    return 0;
}